<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\FhAbout;
use App\Models\FhBanner;
use App\Models\FhCategory;
use App\Models\FhDownload;
use App\Models\FhHonor;
use App\Models\FhKnow;
use App\Models\FhIndex;
use App\Models\FhIndexApp;
use App\Models\FhPage;
use App\Models\FhProduct;
use App\Models\FhProductContent;
use App\Models\FhNews;
use App\Models\FhResource;
use App\Models\FhResourseList;
use App\Models\FhSetting;
use App\Models\FhQuestion;
use App\Models\FhTag;
use App\Models\FhFeedback;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Captcha;
class HomeController extends Controller{
    //首页
    public function Index(){
        $banner = FhBanner::where('show',1)->orderby('sort','desc')->get();
        $info = FhSetting::select('web_name','web_keyword','web_desc','web_about','web_img','app_title','app_bg','app_desc','web_num','web_company')->first();
        $cate = FhCategory::where('show',1)->where('pid',0)->orderby('sort','desc')->get();
        $news = $this->getNews();
        $index_product = FhIndex::where('show',1)->select('name','url','img')->orderby('sort','desc')->get();
        $app = FhIndexApp::where('show',1)->orderby('sort','desc')->limit(9)->get();
        $honor = FhHonor::select('name','thumb','imgst')->get();
        $download = FhDownload::where('show',1)->select('name','b_url','type','f_url','created_at')->orderby('created_at','desc')->limit(5)->get();
        return view('web.index',['cate'=>$cate,'news'=>$news,'info'=>$info,'app'=>$app,'banner'=>$banner,'honor'=>$honor,"index_product"=>$index_product,'down'=>$download]);
    }

    //新闻详情
    public function newsDetail($url){
        
        $news = FhNews::where('url','like','/fongwahnew/'.$url."%")->first();
        $tags = [];
        if(isset($news->tags)){
            $tags = FhTag::wherein('id',explode(',',$news->tags))->select('name','url','c_name')->get();
        }
        $banner = $this->getBanners("/category/fongwahnew");
        $likes = FhNews::where('id','<>',$news->id)->where('type',$news->type)->where('show',1)->orderby('created_at','desc')->limit(6)->select("url",'title','description')->get();
        $hotProduct = FhProduct::where('show',1)->select('thumb','url','name')->orderby('hot','desc')->limit(6)->get();

        $infs = FhNews::where('show',1)->orderby('hot','desc')->select("url",'title','description','thumb')->limit(6)->get();
        return view('web.news-detail',['news'=>$news,'tags'=>$tags,'banner'=>$banner,'like'=>$likes,'product'=>$hotProduct,'infs'=>$infs,'navs'=>['/category/fongwahnew','峰华资讯']]);
    }
    
    public function category(){
        $info = FhPage::where("url",'/project-category/portfolio/')->select('name','keyword','description','htmls',"banner")->first();
         $banner = $this->getBanners("/project-category/portfolio/");
         $cate = FhCategory::where('show',1)->where('pid',0)->orderby('sort','desc')->get();
           return view('web.caetgory-list',['info'=>$info,'cate'=>$cate,'banner'=>$banner]);
    }
    
    
    //新闻详情
    public function newsDetailinformation($url){
        $news = FhNews::where('url','like','/information/'.$url."%")->first();
        $tags = [];
        if(isset($news->tags)){
            $tags = FhTag::wherein('id',explode(',',$news->tags))->select('name','url','c_name')->get();
        }
        $banner = $this->getBanners("/category/information");
        $likes = FhNews::where('id','<>',$news->id)->where('type',$news->type)->where('show',1)->orderby('created_at','desc')->limit(6)->select("url",'title','description')->get();
        $hotProduct = FhProduct::where('show',1)->select('thumb','url','name')->orderby('hot','desc')->limit(6)->get();

        $infs = FhNews::where('show',1)->orderby('hot','desc')->select("url",'title','description','thumb')->limit(6)->get();
        return view('web.news-detail',['news'=>$news,'tags'=>$tags,'banner'=>$banner,'like'=>$likes,'product'=>$hotProduct,'infs'=>$infs,'navs'=>['/category/information',"技术资讯"]]);
    }
    //新闻详情
    public function newsDetailindustry($url){
        $news = FhNews::where('url','like','/industry-info/'.$url."%")->first();
        $tags = [];
        if(isset($news->tags)){
            $tags = FhTag::wherein('id',explode(',',$news->tags))->select('name','url','c_name')->get();
        }
        $banner = $this->getBanners("/category/industry-info");
        $likes = FhNews::where('id','<>',$news->id)->where('type',$news->type)->where('show',1)->orderby('created_at','desc')->limit(6)->select("url",'title','description')->get();
        $hotProduct = FhProduct::where('show',1)->select('thumb','url','name')->orderby('hot','desc')->limit(6)->get();

        $infs = FhNews::where('show',1)->orderby('hot','desc')->select("url",'title','description','thumb')->limit(6)->get();
        return view('web.news-detail',['news'=>$news,'tags'=>$tags,'banner'=>$banner,'like'=>$likes,'product'=>$hotProduct,'infs'=>$infs,'navs'=>['/category/industry-info',"行业资讯"]]);
    }

    //产品列表
    public function productList($url,$sub="",Request $request){
        $tag = new FhCategory();
        $menus = $tag->getCate();
        $where = $url;
        // $banner = $this->getBanners('/project-category/'.$where);
        $path = $request->path();
        // echo "/".$path;
        
        $cate = $tag->where('c_url',"like","%/".$path."%")->where('show',1)->select('id','c_name','pid','c_keyword','c_desc')->first();
        // var_dump($cate);
        if ($cate) {
             $cate = $cate->toArray();
             $banner = $this->getBanners("/".$path);
             $product = new FhProduct();
             $productlist = $product->getProductById($cate['id']);
        } else {
            $cate = null;
            $banner = "";
            $productlist = null;
        }

        // dd($cate);
       

        return view('web.product-list',['info'=>$cate,'banner'=>$banner,'list'=>$productlist]);
    }

    //产品详情
    public function productDeatil($url){
        $productInfo = FhProduct::where('url','/products/'.$url)->first();
        $content = FhProductContent::where('product_id',$productInfo->id)->where('show',1)->select("t_name","t_content")->orderby('sort')->get();
        $showThumb = [];
        $img = explode(",",$productInfo->img);
        foreach($img as $v){
            $thumb=explode(".", $v);
            $showThumb['img'][] = $v;
            $showThumb['thumb'][] = $thumb[0].'-small.'.$thumb[1];
        }
        $pid = [];

        $nav = $this->getcate($pid,$productInfo->pid);
        $nav = json_encode($nav);
        $nav = json_decode($nav,true);

        usort($nav, function($a, $b) {
            return $a['pid'] - $b['pid'];
        });
        $dowloads = [];
        $count = FhResourseList::where('product_id',$productInfo->id)->where('show',1)->count('id');
        if($count>0){
            $dowloads[0]['title'] = "开发包";
            $dowloads[0]['list'] = FhResourseList::where('product_id',$productInfo->id)->where('show',1)->where('r_type',1)->
            select("r_name","r_url","n_url","r_addr","r_desc")->get();
            $dowloads[1]['title'] = "说明书";
            $dowloads[1]['list'] = FhResourseList::where('product_id',$productInfo->id)->where('show',1)->where('r_type',2)->
            select("r_name","r_url","n_url","r_addr","r_desc")->get();
            $dowloads[2]['title'] = "规格书";
            $dowloads[2]['list'] = FhResourseList::where('product_id',$productInfo->id)->where('show',1)->where('r_type',3)->
            select("r_name","r_url","n_url","r_addr","r_desc")->get();
        }
        
        $like = FhProduct::where('id','<>',$productInfo->id)->where('pid',$productInfo->pid)->
        select('name','url','thumb','Introduction')->limit(8)->get();
        return view('web.product-detail',['hash'=>$nav,'info'=>$productInfo,'content'=>$content,'dowload'=>$dowloads,'thumb'=>$showThumb,'like'=>$like]);
    }

    //联系我们
    public function contact(){
        $info = FhPage::where("url",'/contact')->select('name','keyword','description','htmls',"banner")->first();
        return view('web.feedback',['infos'=>$info,'banner'=>$info->banner]);
    }

    //新闻列表
    public function newList($url,Request $request){
        $banner = $this->getBanners('/category/'.$url);
        if($url=="bolg"){
            $name="";
            if($request->input('tag',"")!=""){
                $tag = $request->input('tag',"");
                $pid = FhCategory::where('c_name','like','%'.$tag.'%')->value('id');
                $name = $tag;
                $list = FhQuestion::where('show',1)->where('pid',$pid)->select('thumb','url','title','q_desc','created_at')->orderby('created_at','desc')->paginate(10);
            }else{
                $list = FhQuestion::where('show',1)->select('thumb','url','title','q_desc','created_at')->orderby('created_at','desc')->paginate(10);
            }
            $menus = FhCategory::where('pid',0)->select('c_name')->get();
            
            return view('web.question-list',['list'=>$list,'banner'=>$banner,'name'=>$name,'menus'=>$menus]);
        }else{
            $type = $this->getType($url);
            $list = FhNews::where("type",$type['type'])->where('show',1)->orderby('created_at','desc')->paginate(6);
    
            return view('web.news-list',['list'=>$list,'banner'=>$banner,'info'=>$type]);
        }
    }
    protected function getType($url){
        $pages = FhPage::where("url",'like',"%{$url}%")->select('name','keyword','description')->first();
     
        $type['type'] = 1;
        $type['title'] = $pages->name;
        $type['keyword'] = $pages->keyword==null?"":$pages->keyword;
        $type['description'] = $pages->description==null?"":$pages->description;
        switch ($url) {
            case 'industry-info':
                $type['type'] = 1;
                break;
            case 'fongwahnew':
                $type['type']  = 2;
                break;
            case 'information':
                $type['type']  = 3;
                break;       

        }
        return $type;
       
    }

    //单页面
    public function pages($url,Request $request){
        
        $path = $request->path();
        
        $info = FhPage::where("url","/".$url)->select()->first();
        if(!isset($info->id)){
            $info = FhPage::where("url","/".$url."/")->select()->first();
        }

        $banner = $this->getBanners('/'.$url);
        if($url=="rfid"){
            $cateid = FhCategory::where('show',1)->where('pid',0)->select('id','c_name')->get()->toArray();
            $knowList = [];
            foreach($cateid as $k=>$v){
                $knowList[$k]['title'] = $v['c_name'];
                $knowList[$k]['list'] = FhKnow::where('show',1)->where('pid',$v['id'])->select('id','title','url')->get()->toArray();
            }

            return view("web.know",['info'=>$info,'banner'=>$banner,'list'=>$knowList]);
        }
       
        return view("web.page",['info'=>$info,'banner'=>$banner]);
    }
    
    //知识加油站详情
    public function knowDetail($url){
        $banner = $this->getBanners('/rfid');
        $news = FhKnow::where('url','like','/dt_testimonials/'.$url)->first();
        $likes = FhNews::where('type',$news->type)->where('show',1)->limit(6)->select("url",'title','description')->get();
        $hotProduct = FhProduct::where('show',1)->select('thumb','url','name')->orderby('hot','desc')->limit(6)->get();

        $infs = FhNews::where('type',2)->where('show',1)->orderby('hot','desc')->select("url",'title','description','thumb')->limit(6)->get();
        return view("web.know-detail",['news'=>$news,'banner'=>$banner,'like'=>$likes,'product'=>$hotProduct,'infs'=>$infs]);
    }
    //首页产品单页面
    public function productPage($url){
        $info = FhIndex::where("url","like","/pages/".$url)->select('banners','name','keyword','description','htmls')->first();
        return view("web.pagep",['info'=>$info]);
    }

    public function support($url="sdk"){
        $info = FhPage::where("url",'like','/support/sdk%')->select('id','name','keyword','description','htmls')->first();
       
        $banner = $this->getBanners('/support');
        $cateid = FhResourseList::where('show',1)->groupby("p_id")->pluck('p_id')->toArray();
        $cateList = FhCategory::where('show',1)->where('pid',0)->select('c_name','id')->orderby('sort','desc')->get()->toArray();
        foreach($cateList as $k=>$v){
            
            $ca_list =  FhCategory::where('show',1)->where('pid',$v['id'])->pluck('id')->toArray();
          
            $productid = FhResourseList::where('show',1)->whereIn('p_id',$ca_list)->groupby('product_id')->pluck('product_id')->toArray();
            
            
           foreach($productid as $kk=>$vv){
                $cateList[$k]['product'][$kk]['info'] = FhProduct::where('id',$vv)->select('name','url','thumb')->first()->toArray();
                $cateList[$k]['product'][$kk]['sorce'] =FhResourseList::where('product_id',$vv)->
                select("r_name","r_url","n_url","r_addr")->get()->toArray(); 
           }
            
        }
        return view('web.support',['info'=>$info,'banner'=>$banner,'source'=>$cateList]);

    }

    //标签列表
    public function tag($url){

        $banner = $this->getBanners('/category/industry-info');
        $where = "/tag/".$url."%";
        $tag_info = FhTag::where('url','like',$where)->first();
        $keyword = $tag_info->id;
        //查询新闻中的
        $results = FhNews::where(function ($query) use ($keyword) {
            $query->where('tags', 'like', $keyword . '%')
                ->orWhere('tags', 'like', '%,' . $keyword . '%')
                ->orWhere('tags', 'like', '%,' . $keyword)
                ->orWhere('tags', $keyword);
        })->select('title','url','thumb','description')
        ->get();
        $question = FhQuestion::where(function ($query) use ($keyword) {
            $query->where('tag', 'like', $keyword . '%')
                ->orWhere('tag', 'like', '%,' . $keyword . '%')
                ->orWhere('tag', 'like', '%,' . $keyword)
                ->orWhere('tag', $keyword);
        })->select('title','url','thumb','q_desc as description')
        ->get();

        return view('web.tag-list',['info'=>$tag_info,'banner'=>$banner,'news'=>$results,'question'=>$question]);
    }

    public function question($url){
        $banner = $this->getBanners('/category/bolg');
        $info = FhQuestion::where('url','like',"/blog/".$url."%")->first();
        $likes = FhQuestion::where('id','<>',$info->id)->where('pid',$info->pid)->where('show',1)->limit(6)->select("url",'title','q_desc')->get();
        $hotProduct = FhProduct::where('show',1)->select('thumb','url','name')->orderby('hot','desc')->limit(6)->get();
        $tags = [];
        if(isset($news->tags)){
            $tags = FhTag::wherein('id',explode(',',$info->tag))->select('name','url','c_name')->get();
        }
        $infs = FhNews::where('show',1)->orderby('hot','desc')->select("url",'title','description','thumb')->limit(6)->get();
        return view('web.question-detail',['info'=>$info,'banner'=>$banner,'tags'=>$tags,'like'=>$likes,'banner'=>$banner,'product'=>$hotProduct,'infs'=>$infs]);
    }


    public function feedback(Request $request){
        $rules = ['code' => 'required|captcha'];
        $messages = [
            'code.required' => '验证码不能为空',
            'code.captcha' => '验证码输入错误',
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        $token = $request->_token;
        $code = $request->code;
        // dd($validator->fails());
        if($validator->fails()){
            $errors = $validator->errors();
            // 判断错误类型并返回相应的错误响应
            if ($errors->has('captcha')) {
                return response()->json(["code"=>500,'msg' => $errors->first('captcha')], 200);
            } else {
                // 其他字段的验证错误
                return response()->json(["code"=>500,'msg' => $errors->first()], 200);
            }
        }
        $data['name'] = $request->name;
        $data['email'] = $request->email;
        $data['phone'] = $request->phone;
        $data['inquiry'] = $request->inquiry;
        $data['created_at'] = date('Y-m-d H:i:s',time());
        $feed = new FhFeedback();
        $res = $feed->insertGetId($data);
        if ($res){
            $this->sendEmail($data);
            return response()->json(['code'=>200,'msg'=>'success']);
        }
        return response()->json(['code'=>500,'msg'=>'失败']);
    }
    //发送邮件
    protected function sendEmail($data){
        $mail = new PHPMailer(true);
        try {
            // 配置 SMTP 服务器和认证信息
            $mail->isSMTP();
            $mail->Host = 'smtp.qq.com'; // SMTP 服务器地址
            $mail->SMTPAuth = true;
            $mail->Username = 'xfdada@qq.com'; // SMTP 邮箱地址
            $mail->Password = ''; // SMTP 邮箱密码
            $mail->SMTPSecure = 'tls';
            $mail->CharSet = 'UTF-8';
            $mail->Port = 587;
            // 设置发件人
            $mail->setFrom('xfdada@qq.com', '峰华官网');
            
            // 设置收件人
            $mail->addAddress('xiangfudada@163.com', 'Recipient Name');
            
            // 设置邮件内容
            $mail->isHTML(true);
            $mail->Subject = '用户留言';
            $html = <<<TLS
            <div style="width:100%;"><span style="width:100%;display:block;">姓名:<span><p >{$data['name']}</p></div>
            <div style="width:100%;"><span style="width:100%;display:block;">邮箱:<span><p >{$data['email']}</p></div>
            <div style="width:100%;"><span style="width:100%;display:block;">电话:<span><p >{$data['phone']}</p></div>
            <div style="width:100%;"><span style="width:100%;display:block;">需求:<span><p >{$data['inquiry']}</p></div>
TLS;


            $mail->Body =  $html ;
            // 发送邮件
            $mail->send();
            
            return '邮件发送成功';
        } catch (Exception $e) {
            return '邮件发送失败: ' . $mail->ErrorInfo;
        }
    }
}
